package com.zbw.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class Server {

    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private String clientId;
    private MqttClient client;
    private MqttTopic topic;

    public Server() throws MqttException {
        this.clientId = Config.uuidAsClientID();
        this.client = new MqttClient(Config.HOST, clientId, new MemoryPersistence());
        this.connect();
    }

    private void connect() throws MqttException {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(Config.USERNAME);
        options.setPassword(Config.PASSWORD.toCharArray());
        options.setConnectionTimeout(10);
        options.setKeepAliveInterval(20);

        this.client.setCallback(new Callback());
        this.client.connect(options);

        topic = this.client.getTopic(Config.TOPIC);
    }

    public void publish(MqttMessage message) throws MqttException {
        MqttDeliveryToken token = this.topic.publish(message);
        token.waitForCompletion();
        LOGGER.debug("message deliveried.complete ===> {}", token.isComplete());
    }

    public void close() throws MqttException {
        if (Objects.isNull(this.client)) {
            return;
        }
        this.client.disconnect();
        this.client.close();
    }
}
